﻿using System;
using System.IO;
using System.Text;
using System.Web.Mvc;
using System.Web.UI;

namespace Nasa8x.Mvc.Helpers
{

    //http://www.weirdlover.com/2010/05/19/render-mvc-partial-as-string-no-bologni-on-this-bologni-sandwich-my-friends/

    public static class RenderPartialAsStringHelper
    {

        /// <summary> 
        /// Render a partial as a string. 
        /// </summary> 
        public static string RenderPartialAsString(this ControllerContext ctx, string partialPath)
        {
            var controller = ctx.Controller;
            return RenderPartialAsString(ctx, partialPath, controller.ViewData, controller.TempData);
        }

        /// <summary> 
        /// Render a partial as a string. 
        /// </summary> 
        public static string RenderPartialAsString(this HtmlHelper html, string partialPath)
        {
            return html.RenderPartialAsString(partialPath, null);
        }

        /// <summary> 
        /// Render a partial as a string. 
        /// </summary> 
        public static string RenderPartialAsString(this HtmlHelper html, string partialPath, object model)
        {
            var ctx = html.ViewContext.Controller.ControllerContext;
            return RenderPartialAsString(ctx, partialPath, new ViewDataDictionary(model), new TempDataDictionary());
        }

        /// <summary> 
        /// Render a partial as a string. 
        /// </summary> 
        static string RenderPartialAsString(ControllerContext context, string partialPath, ViewDataDictionary viewData, TempDataDictionary tempData)
        {
            ViewEngineResult result = ViewEngines.Engines.FindPartialView(context, partialPath);

            if (result.View != null)
            {
                StringBuilder sb = new StringBuilder();
                using (StringWriter sw = new StringWriter(sb))
                {
                    using (HtmlTextWriter output = new HtmlTextWriter(sw))
                    {
                        ViewContext viewContext = new ViewContext(context, result.View, viewData, tempData, output);
                        result.View.Render(viewContext, output);
                    }
                }

                return sb.ToString();
            }

            return String.Empty;

        }
    }
}
